<?php

namespace app\admin\controller\business;

use app\common\controller\Backend;

/**
 * 
 */
class Privatesea extends Backend
{
    // 快速查询，搜索指定的哪些字段
    protected $searchFields = 'business.id,nickname,source.name';
    /**
     * 当前控制器下的一个模型属性
     */
    protected $model = null;

    // 初始化
    public function _initialize()
    {
        parent::_initialize();

        // 全局用户模型
        $this->BusinessModel = model('Business.Business');

        // 回访表
        $this->VisitModel = model('Business.Visit');

        $this->AdminModel = model('Admin');

        $this->ReceiveModel = model('Business.Receive');

        $this->SourceModel = model('Business.Source');

        $this->RegionModel = model('Region');

        $this->Adminlist = $this->AdminModel->select();

        $Admindata = [];

        foreach ($this->Adminlist as $k => &$v) {

            $Admindata[$v['id']] = $v['username'];
        }

        $sourclist = $this->SourceModel->select();

        $Sourcdata = [];

        foreach ($sourclist as $val) {

            $Sourcdata[$val['id']] = $val['name'];
        }

        $Sexlist = [0 => '保密', 1 => '男', 2 => '女'];

        $Deallist = [0 => '未成交', 1 => '已成交'];

        $this->view->assign([
            'Admindata' =>  $Admindata,
            'Sourcdata' =>  $Sourcdata,
            'Sexlist' => $Sexlist,
            'Deallist' => $Deallist
        ]);
    }

    // 查看
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);

        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            // 此处将筛选请求中有争议的字段"id"指定为tableA中的id
            $this->changeWhereName("id", "business.id");

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->BusinessModel
                ->with(['source','admin'])
                ->where($where)
                ->where('adminid', $this->auth->id)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->count();  //查询总数

            $list = $this->BusinessModel
                ->with(['source','admin'])
                ->where($where)
                ->where('adminid', $this->auth->id)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();  //查询数据

            foreach ($list as $item) {
                $visit = $this->VisitModel->where('busid', $item['id'])->order('id DESC')->find();
                $item['visit'] =  $visit;
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    // 添加
    public function add()
    {
        if ($this->request->isPost()) {

            $params = $this->request->post('row/a');

            $salt = randstr();

            $password = md5($params['mobile'].$salt);

            $data = [
                'nickname' => $params['nickname'],
                'mobile' => $params['mobile'],
                'gender' => $params['gender'],
                'sourceid' => $params['sourceid'],
                'deal' => $params['deal'],
                'adminid' => $this->auth->id,
                'password' => $password,
                'salt' => $salt
            ];
            
            // 修改省市区
            if($params['region']){
                $region = explode('/',$params['region']);
                if(count($region) < 3){
                    $this->error('请重新选择省市区!');
                }
                $pathcode = $this->RegionModel->where('name',$region[2])->value('parentpath');
                $pathcode = explode(',',$pathcode);
                list($province, $city, $district) = $pathcode;
                $data['province'] = $province;
                $data['city'] = $city;
                $data['district'] = $district;
               
            }

            if ($data) {
                $this->BusinessModel->startTrans();
                $this->ReceiveModel->startTrans();

                $Businessres = $this->BusinessModel->validate("Common/Business/Business")->save($data);

                if ($Businessres === FALSE) {
                    $this->BusinessModel->rollback();
                    $this->error($this->BusinessModel->getError());
                }

                $list = [
                    'applyid' => $this->auth->id,
                    'status' => 'allot',
                    'busid' => $this->BusinessModel->id
                ];

                // 插入领取表
                $Receiveres = $this->ReceiveModel->save($list);

                if ($Receiveres === FALSE) {
                    $this->BusinessModel->rollback();
                    $this->ReceiveModel->rollback();
                    $this->error($this->ReceiveModel->getError());
                }

                if ($Receiveres === FALSE || $Businessres === FALSE) {
                    $this->BusinessModel->rollback();
                    $this->ReceiveModel->rollback();
                    $this->error('添加失败');
                } else {
                    $this->BusinessModel->commit();
                    $this->ReceiveModel->commit();
                    $this->success('添加成功');
                }

            }
        }

        return $this->view->fetch();
    }

    // 编辑
    public function edit($ids = null)
    {
        $row = $this->BusinessModel->find($ids);

        if (!$row) {
            $this->error(__('未找到当前用户'));
            exit;
        }

        // 省份
        $province = $this->RegionModel->where('code', $row['province'])->value('name');
        // 市
        $city = $this->RegionModel->where('code', $row['city'])->value('name');
        // 区
        $district = $this->RegionModel->where('code', $row['district'])->value('name');

        if ($this->request->isPost()) {

            $params = $this->request->post("row/a");

            $data = [
                'id' =>  $ids,
                'nickname' => $params['nickname'],
                'mobile' => $params['mobile'],
                'gender' => $params['gender'],
                'sourceid' => $params['sourceid'],
                'deal' => $params['deal']
            ];

            // 修改密码
            if($params['password']){
                $salt = randstr();
                $data['salt'] = $salt;
                $data['password'] = md5($params['password'].$salt);
            }
            // 修改省市区
            if($params['region']){
                $region = explode('/',$params['region']);
                if(count($region) < 3){
                    $this->error('请重新选择省市区!');
                }
                $pathcode = $this->RegionModel->where('name',$region[2])->value('parentpath');
                $pathcode = explode(',',$pathcode);
                list($province, $city, $district) = $pathcode;
                $data['province'] = $province;
                $data['city'] = $city;
                $data['district'] = $district;
               
            }

            if ($data) {
                $result = $this->BusinessModel->validate("Common/Business/Business.profile")->isUpdate(true)->save($data);

                if ($result === false) {
                    $this->error($this->BusinessModel->getError());
                    exit;
                }

                $this->success();
                exit;
            }
        }

        $region = $province. '/' .$city.'/' .$district;

        $this->assign([
            "row" => $row, 
            'region' => $region
        ]);

        return $this->view->fetch();
    }

    //回收到公海
    public function recovery($ids = null)
    {
        $ids = !empty($ids) ?  explode(',', $ids) : [];

        $row = $this->BusinessModel->column('id');

        foreach ($ids as $item) {
            if (!in_array($item, $row)) {
                $this->error(__('没有找到该用户'));
                exit;
            }
        }
        $list = [];
        $businesslist = [];
        foreach ($ids as $value) {

            $list[] = [
                'applyid' => $this->auth->id,
                'status' => 'recovery',
                'busid' => $value
            ];

            $businesslist[] = [
                'id' => $value,
                'adminid' => null
            ];
        }

        $this->BusinessModel->startTrans();
        $this->ReceiveModel->startTrans();

        // 更新客户表
        $Businessres = $this->BusinessModel->saveAll($businesslist);

        if ($Businessres === FALSE) {
            $this->BusinessModel->rollback();
            $this->error($this->BusinessModel->getError());
        }
        // 插入领取表
        $Receiveres = $this->ReceiveModel->saveAll($list);

        if ($Receiveres === FALSE) {
            $this->BusinessModel->rollback();
            $this->ReceiveModel->rollback();
            $this->error($this->ReceiveModel->getError());
        }

        if ($Receiveres === FALSE || $Businessres === FALSE) {
            $this->BusinessModel->rollback();
            $this->ReceiveModel->rollback();
            $this->error('回收失败');
        } else {
            $this->BusinessModel->commit();
            $this->ReceiveModel->commit();
            $this->success('回收成功');
        }
    }

    // 删除
    public function del($ids = null)
    {
        $ids = !empty($ids) ?  explode(',', $ids) : [];

        $row = $this->BusinessModel->column('id');

        foreach ($ids as $item) {
            if (!in_array($item, $row)) {
                $this->error(__('没有找到该用户'));
                exit;
            }
        }

        $result = $this->BusinessModel->destroy($ids);

        if ($result === false) {
            $this->error($this->BusinessModel->getError());
            exit;
        }

        $this->success('删除成功');
        exit;
    }
    
}